package homework_2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class WordOperation {
	private XWPFDocument doc;
	public WordOperation(String namepath) throws IOException {
		InputStream is = new FileInputStream("test.docx");  
		doc = new XWPFDocument(is);
		is.close();
	}
	public int showTotalChar() {
		 List<XWPFParagraph> paras = doc.getParagraphs();
		    int totalNum = 0;
		    for (XWPFParagraph para : paras) { 
		    	String string = para.getText();
		        totalNum += string.length();
		    }
		 return totalNum;
	}
	public int showParaNum() {
		List<XWPFParagraph> paras = doc.getParagraphs();
	    int emptyNum = 0;
	    for (XWPFParagraph para : paras) { 
	    	String string = para.getText();
	    	if(string.equals("")) {
	    		emptyNum++;
	    		continue;
	    	}
	    }
	    return paras.size() - emptyNum;
	}
	public List<String> showTitle() {
		List<XWPFParagraph> paras = doc.getParagraphs();
		List<String> list = new ArrayList<String>();
	    for (XWPFParagraph para : paras) { 
	    	String style = para.getStyle();
	    	System.out.print("");
	    	if(style != null && style.contains("a")){
	    		list.add(para.getText());
	    	}  
	    }
	    return list;
	}
	public void replaceString(String target, String replacement) throws IOException {
		List<XWPFParagraph> paras = doc.getParagraphs();
	    for (XWPFParagraph para : paras) { 
	    	List<XWPFRun> runs = para.getRuns();
	    	for (int i = 0; i < runs.size(); i++) { 
	    		XWPFRun run = runs.get(i);
                String oneparaString = run.getText(  
                        run.getTextPosition());  
                if (oneparaString.contains(target)) {  
                    oneparaString = oneparaString.replace(  
                    		target, replacement);  
                    run.setText(oneparaString, 0);
                }  
            }  
	    }
	    FileOutputStream outStream = null;  
        outStream = new FileOutputStream("test.docx");  
        doc.write(outStream);  
        outStream.close();  
	}
}
